// electron-dev.js
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');
const axios = require('axios');

// 开发服务器URL
const VITE_DEV_SERVER_URL = 'http://localhost:3000';

// 保持对window对象的全局引用，避免JavaScript对象被垃圾回收时，窗口被自动关闭
let mainWindow;
let wechatProcess;
let wechatRestartAttempts = 0;
const MAX_RESTART_ATTEMPTS = 5;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'src/main/preload.js')
    }
  });

  // 加载开发服务器URL
  mainWindow.loadURL(VITE_DEV_SERVER_URL);

  // 打开开发工具
  mainWindow.webContents.openDevTools();
  
  // 设置NODE_ENV环境变量
  process.env.NODE_ENV = 'development';
  
  // 当窗口关闭时触发
  mainWindow.on('closed', () => {
    mainWindow = null;
    stopWechatService();
  });
}

// 启动微信服务
async function startWechatService() {
  try {
    const wechatExePath = path.join(process.cwd(), 'wrest.exe');
    
    if (!fs.existsSync(wechatExePath)) {
      dialog.showErrorBox('错误', '找不到wrest.exe文件，请确保它在应用程序目录中');
      return false;
    }

    wechatProcess = spawn(wechatExePath, [], {
      detached: false,
      stdio: 'pipe'
    });

    wechatProcess.stdout.on('data', (data) => {
      console.log(`wrest.exe stdout: ${data}`);
      if (mainWindow) {
        mainWindow.webContents.send('wechat-log', data.toString());
      }
    });

    wechatProcess.stderr.on('data', (data) => {
      console.error(`wrest.exe stderr: ${data}`);
      if (mainWindow) {
        mainWindow.webContents.send('wechat-error', data.toString());
      }
    });

    wechatProcess.on('close', (code) => {
      console.log(`wrest.exe process exited with code ${code}`);
      if (mainWindow) {
        mainWindow.webContents.send('wechat-status', { running: false, exitCode: code });
      }
      
      // 如果不是手动关闭，尝试重启
      if (code !== 0 && wechatRestartAttempts < MAX_RESTART_ATTEMPTS) {
        wechatRestartAttempts++;
        console.log(`尝试重启wrest.exe，第${wechatRestartAttempts}次尝试`);
        setTimeout(() => {
          startWechatService();
        }, 5000); // 5秒后重试
      }
    });

    // 等待服务启动
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    // 检查服务是否正常运行
    try {
      const response = await axios.get('http://localhost:7600');
      if (mainWindow) {
        mainWindow.webContents.send('wechat-status', { running: true });
      }
      wechatRestartAttempts = 0; // 重置重启计数
      return true;
    } catch (error) {
      console.error('无法连接到微信服务:', error);
      if (mainWindow) {
        mainWindow.webContents.send('wechat-status', { running: false, error: error.message });
      }
      return false;
    }
  } catch (error) {
    console.error('启动微信服务时出错:', error);
    if (mainWindow) {
      mainWindow.webContents.send('wechat-status', { running: false, error: error.message });
    }
    return false;
  }
}

// 停止微信服务
function stopWechatService() {
  if (wechatProcess) {
    try {
      process.kill(wechatProcess.pid);
    } catch (error) {
      console.error('停止微信服务时出错:', error);
    }
    wechatProcess = null;
  }
}

// 写入禁止微信自动更新的注册表配置
function disableWechatAutoUpdate() {
  try {
    const { execSync } = require('child_process');
    // 创建注册表项禁止微信自动更新
    execSync('reg add "HKCU\\Software\\Tencent\\WeChat" /v NeedUpdateType /t REG_DWORD /d 0 /f');
    console.log('已禁用微信自动更新');
    return true;
  } catch (error) {
    console.error('禁用微信自动更新时出错:', error);
    return false;
  }
}

// 当Electron完成初始化并准备创建浏览器窗口时调用此方法
app.whenReady().then(() => {
  createWindow();
  
  // 禁用微信自动更新
  disableWechatAutoUpdate();
  
  app.on('activate', () => {
    // 在macOS上，当点击dock图标并且没有其他窗口打开时，通常在应用程序中重新创建一个窗口
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

// 当所有窗口关闭时退出应用
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 在应用退出前尝试关闭微信服务
app.on('before-quit', () => {
  stopWechatService();
});

// IPC通信处理
ipcMain.handle('start-wechat-service', async () => {
  return await startWechatService();
});

ipcMain.handle('stop-wechat-service', () => {
  stopWechatService();
  return true;
});

ipcMain.handle('check-wechat-service', async () => {
  try {
    const response = await axios.get('http://localhost:7600');
    return { running: true };
  } catch (error) {
    return { running: false, error: error.message };
  }
});

// 获取微信API接口
ipcMain.handle('get-wechat-api', async (event, endpoint, params) => {
  try {
    const response = await axios.get(`http://localhost:7600${endpoint}`, { params });
    return response.data;
  } catch (error) {
    console.error(`API请求错误 (${endpoint}):`, error);
    throw new Error(error.message);
  }
});

// 发送微信API请求
ipcMain.handle('post-wechat-api', async (event, endpoint, data) => {
  try {
    const response = await axios.post(`http://localhost:7600${endpoint}`, data);
    return response.data;
  } catch (error) {
    console.error(`API请求错误 (${endpoint}):`, error);
    throw new Error(error.message);
  }
}); 